﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace TeamsPortal.DataAccess
{
    public class CategoriesDataAccess : BaseDataAccess
    {
        public ForumCategory Add(ForumCategory category)
        {
            DbCommand cmd = GetCommand("SPCategoriesInsert");
            cmd.AddParameter(Factory, "name", DbType.String, category.Name);
            cmd.AddParameter(Factory, "order", DbType.Int32, category.Order);

            DbParameter idParameter = cmd.AddParameter(Factory, "categoryId", DbType.Int32, null);
            idParameter.Direction = ParameterDirection.Output;

            cmd.SafeExecuteNonQuery();

            if (idParameter.Value != DBNull.Value)
                category.Id = Convert.ToInt32(idParameter.Value);
            else
                throw new DataException("No value for the output parameter: " + idParameter.ParameterName);

            return category;
        }

        /// <summary>
        /// Get all categories (without the forums in it).
        /// </summary>
        /// <returns></returns>
        public List<ForumCategory> GetCategories()
        {
            DbCommand comm = GetCommand("SPCategoriesGetAll");
            DataTable dt = GetTable(comm);

            List<ForumCategory> categoryList = new List<ForumCategory>();
            foreach (DataRow dr in dt.Rows)
            {
                ForumCategory category = new ForumCategory(dr.Get<int>("CategoryId"), dr.GetString("CategoryName"));
                category.Forums = new List<Forum>();
                categoryList.Add(category);
            }

            return categoryList;
        }
    }
}
